#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX 1000
#define NUMTH 4

void *bubble();

pthread_mutex_t mutex[MAX];
int vet[MAX];

void *bubble(void *t){
	int trocou;
	int i = 0;
	int temp;
	int id = (int)t;

	do{
		trocou = 0;
		for(i=0; i < (MAX -1); i++){
			pthread_mutex_lock(&mutex[i]);
			pthread_mutex_lock(&mutex[i+1]);
			if(vet[i+1]<vet[i]){
				temp = vet[i];
				vet[i] = vet[i+1];
				vet[i+1] = temp;
				trocou = 1;
			}
			pthread_mutex_unlock(&mutex[i]);
			pthread_mutex_unlock(&mutex[i+1]);
			
		}
		printf("%d.",id);

	}while(trocou);
  pthread_exit(NULL);
}



int main(int argc, char *argv[])
{		int i;
		pthread_t threads[NUMTH];
  		pthread_attr_t attr;
  		pthread_attr_init(&attr);
  		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

		for(i=0; i< NUMTH; i++){
			pthread_mutex_init(&mutex[i], NULL);	
  		}

		for(i=0; i< MAX; i++){
			vet[i] = random()%100;
			printf("%d*", vet[i]);
		}
		for(i=0 ; i< NUMTH; i++){
			printf("*********************************************\n");
			printf("Criando THREAD = %d\n", i);
			printf("*********************************************\n");
			pthread_create(&threads[i], &attr, bubble, (void *)i);
		}
		 /* Wait for all threads to complete */
 		for (i = 0; i < NUMTH; i++) {

    			pthread_join(threads[i], NULL);
  		}
		printf("*********************************************\n");
		printf("*********************************************\n");
		printf("*********************************************\n");
		for(i=0; i< MAX; i++){
			printf("%d.", vet[i]);
		}
	printf("\n");
  /* Clean up and exit */
		pthread_attr_destroy(&attr);
  		for (i = 0; i < NUMTH; i++) pthread_mutex_destroy(&mutex[i]);
  	
  		pthread_exit (NULL);
}